//
//  MoreStockList.m
//  HZ_New_Stock
//
//  Created by gaotime on 16/5/27.
//  Copyright © 2016年 Zeroing. All rights reserved.
//

#import "HZMoreStockList.h"
#import <QuartzCore/QuartzCore.h>
#import "config.h"
#import "ColorTools.h"
#import "AppInfo.h"
#import "OSTools.h"
#import "QuoteLvData.h"

#define TITLE_SW  0
#define TITLE_WIDTH  0
#define TITLE_SH self.frame.size.height/2
#define TRIGGERPOINT 0//48  //65.0
#define STABLEOFFSET 40
#define DRAGWIDTH  (self.frame.size.width - TITLE_WIDTH)
#define INDICATORLABEL_WIDTH  180
#define INDICATORLABEL_HEIGHT  30
#define INDICATORLABEL_OFFSET  30
#define ACTIVITY_RECT 30
#define ACTIVITY_OFFSET 50//90
#define ROWHEIGHT 59
#define ITEMGAP 0.0
#define LEFT_GAP 10
#define RIGHT_GAP 10
#define MYTitleH [OSTools AppSize].height * 0.0600//40.0
#define MYCounts 3

@implementation MoreStockList
@synthesize m_data_array,m_color_array,m_title_array,pParent,m_tableView,GADragViewDelegate;

/**初始化GADragView
 *
 *  @param CGRect          frame         GADragView的区域大小
 *
 *  @return －
 */
- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    self.backgroundColor = [UIColor clearColor];
    m_title_array = [[NSMutableArray alloc]initWithCapacity:5];
    
    /*添加表格视图*/
    m_tableViewWidth = frame.size.width;
    m_item_width = (m_tableViewWidth-LEFT_GAP-RIGHT_GAP)/MYCounts;
    m_item_gap = ITEMGAP;
    m_rowHeight = ROWHEIGHT;
    
    pTitlesArray = [NSArray arrayWithObjects:@"股票名称",@"现价",@"涨幅", nil];
    pTitleView = [[UIImageView alloc] init];
    pTitleView.frame = CGRectMake(0, 0, self.frame.size.width, MYTitleH);
    pTitleView.backgroundColor = _rgb2uic(0xe9e9e9, 1);
    [self addSubview:pTitleView];
    
    for (int i = 0; i < pTitlesArray.count; i++) {
      
      CGFloat titleLabelW = m_item_width;
      CGFloat titleLabelH = MYTitleH;
      CGFloat titleLabelX = i * titleLabelW+LEFT_GAP;
      CGFloat titleLabelY = 0;
      
      if (i < pTitlesArray.count-1) {
        UIButton* eButton = [[UIButton alloc]init];
        //按钮填充整个视图
        eButton.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
          eButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
          [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,0,0,0)];
        if (i==0) {
          eButton.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
          eButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        } else if (i==1) {
            eButton.frame = CGRectMake(titleLabelX + 20, titleLabelY, titleLabelW, titleLabelH);
            eButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        }
        [eButton addTarget:self action:@selector(pressedUpDown:) forControlEvents:UIControlEventTouchUpInside];
        //把节号保存到按钮tag，以便传递到expandButtonClicked方法
        eButton.tag = i;
        //设置分组标题
        [eButton setTitle:pTitlesArray[i] forState:UIControlStateNormal];
        [eButton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
        
        [self addSubview:eButton];
        [m_title_array addObject:eButton];
      }else{
        lastButton = [[UIButton alloc]init];
        //按钮填充整个视图
        lastButton.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
        [lastButton addTarget:self action:@selector(pressedUpDown:) forControlEvents:UIControlEventTouchUpInside];
        //把节号保存到按钮tag，以便传递到expandButtonClicked方法
        lastButton.tag = i;
        //设置分组标题
        [lastButton setTitle:pTitlesArray[i] forState:UIControlStateNormal];
//        lastButton.titleLabel.font = KTableView_cell_title_Font;
        [lastButton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
        [lastButton setTitleEdgeInsets:UIEdgeInsetsMake(0,0,0,0)];
        //设置button的图片和标题的相对位置 4个参数是到上边界，左边界，下边界，右边界的距离
        lastButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        
        [self addSubview:lastButton];
        [m_title_array addObject:lastButton];
      }
    }
    
    UIView *line0=[[UIView alloc] initWithFrame:CGRectMake(0, ROWHEIGHT-0.5, self.frame.size.width, 0.5)];
    line0.backgroundColor=_rgb2uic(0xe9e9e9, 1.0);
//    [self addSubview:line0];
    
    /*添加scrollView*/
    m_baseScrollView = [[UIScrollView alloc] initWithFrame:
                        CGRectMake(0, MYTitleH, DRAGWIDTH, self.frame.size.height-MYTitleH)];
    m_baseScrollView.scrollEnabled = YES;
    m_baseScrollView.contentSize = CGSizeMake(DRAGWIDTH,self.frame.size.height-MYTitleH);
    [self addSubview:m_baseScrollView];
    m_baseScrollView.delegate = self;
    m_baseScrollView.backgroundColor = [UIColor clearColor];
      
    m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,DRAGWIDTH,m_baseScrollView.frame.size.height)];
    [m_baseScrollView addSubview:m_tableView];
    self.backgroundColor = [UIColor clearColor];
    
    m_tableView.backgroundColor = [UIColor clearColor];
    m_tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    m_tableView.separatorColor=	_rgb2uic(0xe9e9e9,1);
    
    /*设置代理*/
    m_tableView.delegate = self;// fmy 14.8.27
    m_tableView.dataSource = self;
//    m_tableView.bounces = NO;
    self.userInteractionEnabled = YES;
    
    /*添加数据刷新等待视图*/
    m_activityIndicator = [[UIActivityIndicatorView alloc]
                           initWithActivityIndicatorStyle:
                           UIActivityIndicatorViewStyleWhiteLarge];
    [m_tableView addSubview:m_activityIndicator];
    /*添加显示当前tableView拖拽状态的标签（在tableView的上方）*/
    m_statusLabel_top = [[UILabel alloc] initWithFrame:
                         CGRectMake((m_baseScrollView.frame.size.width
                                     - INDICATORLABEL_WIDTH)/2
                                    + INDICATORLABEL_OFFSET,
                                    -STABLEOFFSET + INDICATORLABEL_HEIGHT/2,
                                    INDICATORLABEL_WIDTH,
                                    INDICATORLABEL_HEIGHT)];
    m_statusLabel_top.backgroundColor = [UIColor clearColor];
    m_statusLabel_top.textColor = [UIColor blackColor];
    [m_tableView addSubview:m_statusLabel_top];
    /*添加显示当前tableView拖拽状态的标签（在tableView的下方）*/
    m_statusLabel_bottom = [[UILabel alloc] init];
    m_statusLabel_bottom.backgroundColor = [UIColor clearColor];
    m_statusLabel_bottom.textColor = [UIColor blackColor];
    [m_tableView addSubview:m_statusLabel_bottom];
    
    //在此处调用一下就可以啦 ：此处假设tableView的name叫：tableView
    [self setExtraCellLineHidden:m_tableView];
    
    m_sortImageView = [UIImageView new];
    m_sortUpImg = [UIImage imageNamed:@"arrow_up"];
    m_sortDownImg = [UIImage imageNamed:@"arrow_down"];
    [self addSubview:m_sortImageView];
    m_tempsorttag = m_sortTag = -1;
    
    bIsFirst_TwoRow = YES;
    
    //    [self initData];
    [self viewDidLayoutSubviews];
  }
  
  return self;
}

-(void)viewDidLayoutSubviews
{
  if ([self.m_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [self.m_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
  }
  
  if ([self.m_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [self.m_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
  }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
    [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
  }
  
  if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
  }
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    /*判断tableView滑动方向*/
    if (scrollView.contentOffset.y > 0) {//向上滑
        m_direction = 1;
    }else{//向下滑
        m_direction = 0;
    }
    
    if (scrollView.isDragging) {
        BOOL _loading = NO;
        
        /*tableView向上滑动时*/
        if (m_direction == 1) {
            float scrY = scrollView.contentOffset.y;
//            UIDevice *device = [UIDevice currentDevice];
//            UIDeviceOrientation orient = device.orientation;
            if (IPHONE5) {
                if (nState == GAPullRefreshPulling &&
                    scrollView.contentOffset.y > (m_hidden_part)
                    && scrollView.contentOffset.y < (m_hidden_part + TRIGGERPOINT)
                    && !_loading) {
                    [self setState:GAPullRefreshNormal withMessage:nil];
                }else if (nState == GAPullRefreshNormal &&
                           scrollView.contentOffset.y > (m_hidden_part + TRIGGERPOINT)
                           && !_loading) {
                    [self setState:GAPullRefreshPulling withMessage:nil];
                }
            }else{// 不是iPhone5
                if (nState == GAPullRefreshPulling &&
                    scrollView.contentOffset.y > (m_hidden_part)
                    && scrollView.contentOffset.y < (m_hidden_part + TRIGGERPOINT)
                    && !_loading) {
                    [self setState:GAPullRefreshNormal withMessage:nil];
                }else if (nState == GAPullRefreshNormal &&
                           scrollView.contentOffset.y > (m_hidden_part + TRIGGERPOINT)
                           && !_loading) {
                    [self setState:GAPullRefreshPulling withMessage:nil];
                }
            }
        }else {/*tableView向下滑动时*/
            float scrY = scrollView.contentOffset.y;
            if (nState == GAPullRefreshPulling &&
                scrollView.contentOffset.y > -TRIGGERPOINT
                && scrollView.contentOffset.y < 0.0f
                && !_loading) {
                [self setState:GAPullRefreshNormal withMessage:nil];
            }else if (nState == GAPullRefreshNormal
                       && scrollView.contentOffset.y < -TRIGGERPOINT
                       && !_loading) {
                [self setState:GAPullRefreshPulling withMessage:nil];
            }
        }
    }
}

/**设置tableView的拖拽状态
 *
 *  @param GAPullRefreshState        aState          tableView拖拽状态
 *  @param NSString                  *aMessage       需要显示的信息
 *
 *  @return －
 */
- (void)setState:(GAPullRefreshState)aState withMessage:(NSString*)aMessage {
  switch (aState) {
    case GAPullRefreshPulling:
      m_statusLabel_top.text = NSLocalizedString(@"释放立即刷新...",  @"Release to refresh status");
      m_statusLabel_bottom.text = NSLocalizedString(@"释放立即刷新...", @"Release to refresh status");
      break;
    case GAPullRefreshNormal:
      m_statusLabel_top.text = NSLocalizedString(@"下拉显示上一页", @"Pull down to refresh status");
      m_statusLabel_bottom.text = NSLocalizedString(@"上拉显示下一页", @"Pull up to refresh status");
      break;
    case GAPullRefreshLoading:
      if (isBegEnd) {
        m_statusLabel_top.text = aMessage;
        m_statusLabel_bottom.text = aMessage;
      }else {
        m_statusLabel_top.text = NSLocalizedString(@"刷新...", @"Loading Status");
        m_statusLabel_bottom.text = NSLocalizedString(@"刷新...",@"Loading Status");
      }
      break;
    default:
      break;
  }
  if(nThemeId == 0){
    m_statusLabel_top.textColor = [UIColor blackColor];
    m_statusLabel_bottom.textColor = [UIColor blackColor];
  }else{
    m_statusLabel_top.textColor = _rgb2uic(0x8c96b4, 1);;
    m_statusLabel_bottom.textColor = _rgb2uic(0x8c96b4, 1);;
  }

  nState = aState;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate {
    BOOL _loading = NO;
    float scrY = scrollView.contentOffset.y;
  /*tableView向下停止滑动后...*/
  if (scrollView.contentOffset.y <= - TRIGGERPOINT && !_loading) {
    [self setState:GAPullRefreshLoading withMessage:nil];
    //将dragViewScrollToTop方法用协议回调出去共其他类使用
    [GADragViewDelegate dragViewScrollToBottom:self];
    /*刷新时维持tableView的偏移状态，y轴偏移量为STABLEOFFSET*/
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
    [UIView commitAnimations];
    /*设置数据刷新等待视图的位置并开启等待状态*/
    [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                              - ACTIVITY_RECT)/2
                                             - ACTIVITY_OFFSET,
                                             -STABLEOFFSET + ACTIVITY_RECT/2 - 15 ,
                                             ACTIVITY_RECT,
                                             ACTIVITY_RECT)];
    [m_activityIndicator startAnimating];
  }
  /*tableView向上停止滑动后...*/
  
  // fmy 14.8.29
  UIDevice *device = [UIDevice currentDevice];
  UIDeviceOrientation orient = device.orientation;
  if (IPHONE5) {
    float height = m_tableView.frame.size.height;
    height = scrollView.contentOffset.y;
      if (scrollView.contentOffset.y >= (m_tableView.frame.size.height + TRIGGERPOINT )
          && !_loading) {
        [self setState:GAPullRefreshLoading withMessage:nil];
        //将dragViewScrollToTop方法用协议回调出去共其他类使用
        [GADragViewDelegate dragViewScrollToTop:self];
        /*刷新时维持tableView的偏移状态，y轴偏移量为-(STABLEOFFSET + m_hidden_part)*/
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        scrollView.contentInset = UIEdgeInsetsMake(0.0f,0.0f, 0.0f, 0.0f);
        [UIView commitAnimations];
        /*开启等待状态*/
        if ([self.m_data_array count]*ROWHEIGHT > m_tableView.frame.size.height) {
          m_hidden_part = ([self.m_data_array count]+1)*ROWHEIGHT
          - m_tableView.frame.size.height;
          [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                                    - ACTIVITY_RECT)/2
                                                   - ACTIVITY_OFFSET,
                                                   11*ROWHEIGHT
                                                   - STABLEOFFSET/2,
                                                   ACTIVITY_RECT,
                                                   ACTIVITY_RECT)];
        }else {
          [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                                    - ACTIVITY_RECT)/2
                                                   - ACTIVITY_OFFSET,
                                                   m_tableView.frame.size.height
                                                   - STABLEOFFSET/2,
                                                   ACTIVITY_RECT,
                                                   ACTIVITY_RECT)];
        }
        [m_activityIndicator startAnimating];
      }
  }else{// 不是iPhone5
      if (scrollView.contentOffset.y >= ( TRIGGERPOINT )&& !_loading) {
        [self setState:GAPullRefreshLoading withMessage:nil];
        //将dragViewScrollToTop方法用协议回调出去共其他类使用
        [GADragViewDelegate dragViewScrollToTop:self];
        /*刷新时维持tableView的偏移状态，y轴偏移量为-(STABLEOFFSET + m_hidden_part)*/
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];
        scrollView.contentInset = UIEdgeInsetsMake(-STABLEOFFSET + 5,0.0f, 0.0f, 0.0f);
        [UIView commitAnimations];
        /*开启等待状态*/
        if ([self.m_data_array count]*ROWHEIGHT > m_tableView.frame.size.height) {
          m_hidden_part = ([self.m_data_array count]+1)*ROWHEIGHT
          - m_tableView.frame.size.height;
          [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                                    - ACTIVITY_RECT)/2
                                                   - ACTIVITY_OFFSET,
                                                   11*ROWHEIGHT
                                                   - STABLEOFFSET/2,
                                                   ACTIVITY_RECT,
                                                   ACTIVITY_RECT)];
        }else {
          [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                                    - ACTIVITY_RECT)/2
                                                   - ACTIVITY_OFFSET,
                                                   m_tableView.frame.size.height
                                                   - STABLEOFFSET/2,
                                                   ACTIVITY_RECT,
                                                   ACTIVITY_RECT)];
        }
        [m_activityIndicator startAnimating];
      }
  }
}

/**tableView刷新数据完成后将y轴的偏移距离弹回
 *
 *  @param UIScrollView        scrollView          scrollView对象
 *
 *  @return －
 */
- (void)refreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationDuration:.3];
//  [scrollView setContentInset:UIEdgeInsetsZero];
  [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
  scrollView.contentOffset = CGPointMake(0, 0);
  m_tableView.contentOffset = CGPointMake(0, 0);//不满一页时上部空白
  [UIView commitAnimations];
  [self setState:GAPullRefreshNormal withMessage:nil];
}


/**tableView接受数据完成取消y轴偏移距离
 *
 *  @param -
 *
 *  @return －
 */
- (void)dismissDragTableViewAnimation {
  [self performSelector:@selector(doneLoadingTableViewData)
             withObject:nil
             afterDelay:0.0];
}


/**tableView接受数据完成
 *
 *  @param -
 *
 *  @return －
 */
- (void)doneLoadingTableViewData {
  [m_activityIndicator stopAnimating];
  m_statusLabel_top.text = @"";
  m_statusLabel_bottom.text = @"";
  [self refreshScrollViewDataSourceDidFinishedLoading:m_baseScrollView];
    
    if (self.m_data_array.count <= 0) {
        return;
    }
  //翻页滚动条置顶
  NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
  [m_tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
  [self setNeedsUpdateConstraints];
}

/**当当前已经是首页或者末页时给出提示
 *
 *  @param NSString                *aString         提示信息
 *  @param GAPullingReachState     aMode            当前是首页或者末页的状态
 *
 *  @return －
 */
- (void)showMessage:(NSString*)aString withMode:(GAPullingReachState)aMode {
    isBegEnd = YES;
//    if (aMode == GAPullingReachBegin) {
//        [self setState:GAPullRefreshLoading withMessage:aString];
//    }
//    if (aMode == GAPullingReachEnd) {
//        [self setState:GAPullRefreshLoading withMessage:aString];
//    }
//    isBegEnd = NO;
}

//add xzm 20130411
/**更新GADragBar的区域位置
 *
 *  @param CGRect        rect          区域
 *
 *  @return －
 */
- (void)updateDragViewFrame{
//  self.frame = rect;
  //  self.frame = CGRectMake(0, 0,self.frame.size.width,self.frame.size.height);
  m_tableViewWidth = self.frame.size.width;
  m_item_width = self.frame.size.width/pTitlesArray.count;
  
  // fmy 14.8.26
//  pTitleView.frame = CGRectMake(0, 0, 0, 0);
  for (int i = 0; i < MYCounts; i++) {
    UILabel *titleLabel = pTitleView.subviews[i];
    CGFloat titleLabelW = m_item_width;
    CGFloat titleLabelH = MYTitleH;
    CGFloat titleLabelX = i * titleLabelW;
    CGFloat titleLabelY = 0;
    titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
  }
  
//  [self.m_tableView reloadData];
}
//add end xzm 20130411


//-(void)setProperty:(UIColor*)aSeparatorColor with:(UIColor*)aCellColor1 with:(UIColor*)aCellColor2{
//  self.m_tableView.separatorColor = aSeparatorColor;
//  cellbgColor1 = [aCellColor1 retain];
//  cellbgColor2 = [aCellColor2 retain];
//}

/**重新设置底端状态标签和等待视图的位置
 *
 *  @param int        nRowCount        tableView的行数
 *
 *  @return －
 */
- (void)resetFrame:(int)nRowCount {
  if (nRowCount*ROWHEIGHT + ROWHEIGHT > m_tableView.frame.size.height) {
    m_hidden_part = (nRowCount + 1)*ROWHEIGHT - m_tableView.frame.size.height;
    
    [m_statusLabel_bottom setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                               - INDICATORLABEL_WIDTH)/2
                                              + INDICATORLABEL_OFFSET,
                                              nRowCount*ROWHEIGHT
                                              + STABLEOFFSET/2
                                              - INDICATORLABEL_HEIGHT/2 ,
                                              INDICATORLABEL_WIDTH,
                                              INDICATORLABEL_HEIGHT)];
    
    [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                              - ACTIVITY_RECT)/2
                                             - ACTIVITY_OFFSET,
                                             nRowCount*ROWHEIGHT
                                             + STABLEOFFSET/2
                                             - INDICATORLABEL_HEIGHT/2 + ROWHEIGHT,
                                             ACTIVITY_RECT,
                                             ACTIVITY_RECT)];
    m_scrollInsets = UIEdgeInsetsMake(-(STABLEOFFSET + m_hidden_part),
                                      0.0f, 0.0f, 0.0f);
  }
  else {
    m_hidden_part = 0;
    
    [m_statusLabel_bottom setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                               - INDICATORLABEL_WIDTH)/2
                                              + INDICATORLABEL_OFFSET,
                                              m_tableView.frame.size.height
                                              + STABLEOFFSET/2
                                              - INDICATORLABEL_HEIGHT/2,
                                              INDICATORLABEL_WIDTH,
                                              INDICATORLABEL_HEIGHT)];
    
    [m_activityIndicator setFrame:CGRectMake((m_baseScrollView.frame.size.width
                                              - ACTIVITY_RECT)/2
                                             - ACTIVITY_OFFSET,
                                             m_tableView.frame.size.height
                                             + STABLEOFFSET/2
                                             - INDICATORLABEL_HEIGHT/2,
                                             ACTIVITY_RECT,
                                             ACTIVITY_RECT)];
    m_scrollInsets = UIEdgeInsetsMake(-STABLEOFFSET,0.0f, 0.0f, 0.0f);
  }
}

/**设置StockList的数据
 *
 *  @param NSMutableArray       *aData             数据数组
 *  @param NSMutableArray       *aColorArray       颜色数组
 *
 *  @return －
 */
- (void)setStockListData:(NSMutableArray*)aData
               withColor:(NSMutableArray*)aColorArray {
  
  // *2014.11.25 fmy
  [self.m_data_array removeAllObjects];
  self.m_data_array = aData;
  
  if ([aData count] != [aColorArray count] || [aData count] == 0) {
    [self.m_tableView reloadData];
    return;
  }
  // *end
  
  self.m_color_array = aColorArray;
  m_item_count = [[self.m_data_array objectAtIndex:0] count]-1;//最后一个字段传的是股票结构信息或板块ID
  m_rowHeight = ROWHEIGHT;
  //  m_VisibleItemCount = self.m_data_array.count;
  //
  //  self.frame = CGRectMake(0,0,m_tableViewWidth,(m_VisibleItemCount +1)*ROWHEIGHT);
  
  [self resetFrame:self.m_data_array.count];
  [self.m_tableView reloadData];
}

/**设置tableView的背景图片
 *
 *  @param -
 *
 *  @return －
 */
- (void)setBackgroundImage:(UIImage*)aBackgroundImage {
  self.backgroundColor = [UIColor colorWithPatternImage:aBackgroundImage];
}

#pragma mark
#pragma mark UITableViewDataSource 委托方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return ([self.m_data_array count]);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return m_rowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	 
  
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                           CellIdentifier];
  //  UITableViewCell *cell = nil;
  if (cell == nil) {
    cell = [self tableviewCellWithReuseIdentifier:CellIdentifier
                                        IndexPath:indexPath];
    
  }else {
    [cell removeFromSuperview];
    cell = [self tableviewCellWithReuseIdentifier:CellIdentifier
                                        IndexPath:indexPath];
  }
  
  cell.selectionStyle = UITableViewCellSelectionStyleNone;
  cell.contentView.backgroundColor = [UIColor whiteColor];
  cell.backgroundColor = [UIColor colorWithRed:193.0/255.0 green:193.0/255.0 blue:193.0/255.0 alpha:1.0];
  if(nThemeId==1){
    cell.contentView.backgroundColor = _rgb2uic(0x2e303f,1);
    cell.backgroundColor = _rgb2uic(0x2e303f,1);
  }
  
  if (IOS7_OR_LATER) {
    [tableView setSeparatorInset:(UIEdgeInsetsZero)];
  }
  
  // Configure the cell.
  [self configureCell:cell forIndexPath: (NSIndexPath *)indexPath];
  
  return cell;
}


/**获取tableView的父视图
 *
 *  @param NSString        identifier         cell的重用标记
 *  @param NSIndexPath     indexPath          表格的row索引
 *
 *  @return UITableViewCell  *cell
 */
- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier
                                            IndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [[UITableViewCell alloc]
                            initWithStyle:UITableViewCellStyleDefault
                            reuseIdentifier:identifier];
  
  if (m_item_count == 0) {
    return cell;
  }
  
  //item的横坐标
  float a_item_x = LEFT_GAP;
  if (bIsFirst_TwoRow) {
    for (int i = 0; i < m_item_count; i++) {
      UILabel *item = [[UILabel alloc] initWithFrame:
                       CGRectMake(a_item_x, 0, m_item_width, ROWHEIGHT)];
      item.textAlignment = NSTextAlignmentRight;
      
      if (i==0) {
        item.frame = CGRectMake(10, 10, m_item_width, (ROWHEIGHT-20)*3/5);
        item.textAlignment = NSTextAlignmentLeft;
      }else if (i==1){
        item.frame = CGRectMake(10, (ROWHEIGHT-20)*3/5 + 10, m_item_width, (ROWHEIGHT-20)*2/5);
        item.textAlignment = NSTextAlignmentLeft;
      }
      
      item.tag = i + 1;
      item.backgroundColor = [UIColor clearColor];
      
      if (i == 2 || i == 3) {
        item.frame = CGRectMake(a_item_x+ITEMGAP, 0, m_item_width-2*ITEMGAP, ROWHEIGHT);
      }
        if (i == 3) {
            item.textAlignment = NSTextAlignmentRight;
        }
      
      //    if (i == m_item_count-1) {
      //      item.frame = CGRectMake(a_item_x+5, 5, m_item_width-10, ROWHEIGHT-10);
      //    }
      
      if(i==0){
        //        item.frame = CGRectMake(a_item_x+8, 0, m_item_width+10, ROWHEIGHT);
        UIButton* rButton = [[UIButton alloc]init];
        //按钮填充整个视图
        rButton.frame = CGRectMake(LEFT_GAP-30, 8, 15, 15);
        [rButton setImage:[UIImage imageNamed:@"" ]forState:UIControlStateNormal];
        //设置button的图片和标题的相对位置 4个参数是到上边界，左边界，下边界，右边界的距离
        [item addSubview:rButton];
//        [rButton release];
      }
      [cell.contentView addSubview:item];
      
      if (i != 1) {
        //计算下一个item的横坐标
        a_item_x += m_item_width -1;
      }
      
//      [item release];
    }
  }else{
    for (int i = 0; i < m_item_count; i++) {
      UILabel *item = [[UILabel alloc] initWithFrame:
                       CGRectMake(a_item_x, 0, m_item_width, ROWHEIGHT)];
      item.textAlignment = NSTextAlignmentRight;
//      item.font = KTableView_cell_data_Font;
      
      if (i==0) {
        item.frame = CGRectMake(10, 0, m_item_width, ROWHEIGHT);
        item.textAlignment = NSTextAlignmentLeft;
      }
      
      item.tag = i + 1;
      item.backgroundColor = [UIColor clearColor];
      
      if (i == 1 || i == 2) {
        item.frame = CGRectMake(a_item_x+ITEMGAP, 0, m_item_width-2*ITEMGAP, ROWHEIGHT);
      }
      
      if(i==0){
        //        item.frame = CGRectMake(a_item_x+8, 0, m_item_width+10, ROWHEIGHT);
        UIButton* rButton = [[UIButton alloc]init];
        //按钮填充整个视图
        rButton.frame = CGRectMake(LEFT_GAP-30, 8, 15, 15);
        [rButton setImage:[UIImage imageNamed:@"" ]forState:UIControlStateNormal];
        //设置button的图片和标题的相对位置 4个参数是到上边界，左边界，下边界，右边界的距离
        [item addSubview:rButton];
//        [rButton release];
      }
      [cell.contentView addSubview:item];
      
      //计算下一个item的横坐标
      a_item_x += m_item_width -1;
      
//      [item release];
    }
  }
  
  if(nThemeId==1){
    cell.contentView.backgroundColor = _rgb2uic(0x2e303f,1);
    cell.backgroundColor = _rgb2uic(0x2e303f,1);
  }
  
  return cell;
}


/**设置tableView的数据
 *
 *  @param UITableViewCell        cell               表格视图的cell
 *  @param NSIndexPath            indexPath          表格的row索引
 *
 *  @return －
 */
- (void)configureCell:(UITableViewCell *)cell
         forIndexPath:(NSIndexPath *)indexPath {
  NSUInteger row = [indexPath row];
  
  if (m_item_count == 0) {
    return;
  }
  
  if ([[self.m_data_array objectAtIndex:row] isKindOfClass:[NSString class]]){
    if ([[self.m_data_array objectAtIndex:row] isEqualToString:@""]) {
      return;
    }
  }
  
  UILabel *a_stockName = (UILabel*)[cell.contentView viewWithTag:1];
  NSString *title = [[self.m_data_array objectAtIndex:row] objectAtIndex:0];
  NSString *string2 = [title substringToIndex:1];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"code" ofType:@"plist"];
    NSArray *codeArray = [[NSArray alloc] initWithContentsOfFile:path];
    if(codeArray.count>indexPath.row){
        NSDictionary *infoDic = codeArray[indexPath.row];
        title = NotNilStr(infoDic[@"name"]);
    }else{
        NSDictionary *infoDic = codeArray[0];
        title = NotNilStr(infoDic[@"name"]);
    }
    a_stockName.text = title;
    a_stockName.textColor = [[self.m_color_array objectAtIndex:row] objectAtIndex:0];
    a_stockName.font = [UIFont systemFontOfSize:17];
  // *2014.12.3 fmy
  a_stockName.numberOfLines = 0;
  // *end
		
//  UILabel *a_stockPrice = (UILabel*)[cell.contentView viewWithTag:2];
//  a_stockPrice.text = [[self.m_data_array objectAtIndex:row] objectAtIndex:1];
//  a_stockPrice.textColor = [[self.m_color_array objectAtIndex:row] objectAtIndex:1];
//  a_stockPrice.backgroundColor =[UIColor clearColor];
  
  for (int i = 0; i < m_item_count-1; i++) {
    
    UILabel *item = (UILabel*)[cell.contentView viewWithTag:(i + 2)];
    item.text = [[self.m_data_array objectAtIndex:row] objectAtIndex:(1 + i)];
    item.textColor = [[self.m_color_array objectAtIndex:row] objectAtIndex:(1 + i)];
    item.backgroundColor =[UIColor clearColor];
      if (i == 0) {
          item.font = [UIFont systemFontOfSize:12];
      }else {
          item.font = [UIFont systemFontOfSize:20];
      }
      UILabel *socklabel = (UILabel*)[cell.contentView viewWithTag:2];
      socklabel.hidden = YES;
  }
  
}


//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//  
//  NSUInteger row = [indexPath row];
//  if(pParent!=nil){
//    [pParent OnAction:self withType:ACTIVE_LIST_CLICKED withArg:self.m_data_array[row]];
//  }
//}

/**清除数据
 *
 *  @param -
 *
 *  @return －
 */
- (void)clearData {
  [self initData];
  self.m_color_array = nil;
  [self.m_tableView reloadData];
}

/**初始化数据
 *
 *  @param -
 *
 *  @return －
 */
- (void)initData {
  NSMutableArray *a_tempArray = [[NSMutableArray alloc] initWithObjects:
                                 @"",@"",@"",@"",nil];
  self.m_data_array = a_tempArray;
//  [a_tempArray release];
  if ([self.m_title_array count]>0) {
    m_item_count = [self.m_title_array count];
  }
  else {
    m_item_count = 0;
  }
}

- (void)setTitle:(NSArray*)aTitleArray withFirstCol:(BOOL)bTwoRow{
//  self.m_title_array = aTitleArray;
//  if ([self.m_title_array count]>0) {
//    m_item_count = [self.m_title_array  count];
//  }
//  else {
//    m_item_count = 0;
//  }
//  [self.m_tableView reloadData];
  if (aTitleArray.count != m_title_array.count) {
    return;
  }
  bIsFirst_TwoRow = bTwoRow;
  for (int i = 0; i < aTitleArray.count; i++) {
    UIButton *button = self.m_title_array[i];
    [button setTitle:aTitleArray[i] forState:UIControlStateNormal];
//    button.titleLabel.text = aTitleArray[i];
  }
}

-(void)setSortMode:(SORT_MODE)n withTag:(NSUInteger)aTag{
  m_sortTag = aTag;
  m_sortMode = n;
  switch (m_sortMode) {
    case DATAGRID_SORT_UP:
      m_sortImageView.image = [UIImage imageNamed:@"arrow_up"];
      break;
    case DATAGRID_SORT_DOWN:
      m_sortImageView.image = [UIImage imageNamed:@"arrow_down"];
      break;
    default:
      m_sortImageView.image = [UIImage imageNamed:@""];
      break;
  }
}

-(SORT_MODE)getSortMode{
  return m_sortMode;
}

-(void)pressedUpDown:(UIButton *)aButton{
  if (!bIsDataSort) {
    return;
  }
  m_sortTag = aButton.tag;
  if (aButton.tag == 0) {
    return;
  }
  if (m_sortTag == m_tempsorttag) {
    if (m_sortMode == DATAGRID_SORT_UP) {
      [self setSortMode:DATAGRID_SORT_DOWN withTag:aButton.tag];
    }else{
      [self setSortMode:DATAGRID_SORT_UP withTag:aButton.tag];
    }
  }else{
    m_tempsorttag = m_sortTag;
    [self setSortMode:DATAGRID_SORT_DOWN withTag:aButton.tag];
  }
  
  UIImage *image = [UIImage imageNamed:@"listctrl_d"];
  m_sortImageView.frame = CGRectMake(aButton.frame.origin.x+aButton.frame.size.width+2, (MYTitleH-image.size.height)/2, image.size.width, image.size.height);
  NSString *btnTag = [NSString stringWithFormat:@"%d",(int)aButton.tag-1];
  [self.parent upToParentWithObjc:self withType:kHZ_ClickDataGridHead_Action withParamter:btnTag];
}

-(void)setDefaultSort:(BOOL)bIsSort{
  m_sortTag = lastButton.tag;
  if (lastButton.tag == 0) {
    return;
  }

  m_tempsorttag = m_sortTag;
  bIsDataSort = bIsSort;
  if (bIsSort) {
    [self setSortMode:DATAGRID_SORT_DOWN withTag:lastButton.tag];
  }else{
    [self setSortMode:DATAGRID_SORT_NONE withTag:lastButton.tag];
  }
  
  if (bIsSort) {
    for (int i = 1; i < m_title_array.count; i++) {
      UIButton *button = m_title_array[i];
      button.userInteractionEnabled=YES;
    }
  }else{
    for (int i = 1; i < m_title_array.count; i++) {
      UIButton *button = m_title_array[i];
      button.userInteractionEnabled=NO;
    }
  }
  
  UIImage *image = [UIImage imageNamed:@"listctrl_d"];
  m_sortImageView.frame = CGRectMake(lastButton.frame.origin.x+lastButton.frame.size.width+2, (MYTitleH-image.size.height)/2, image.size.width, image.size.height);
}

-(void)setExtraCellLineHidden: (UITableView *)tableView
{
  UIView *view = [UIView new];
  view.backgroundColor = [UIColor clearColor];
  [tableView setTableFooterView:view];
//  [view release];
}

-(void)setPageInfo:(NSUInteger)aCurrentPage withCount:(NSUInteger)aTotolPage{
//  [m_pageInfo release];
  m_pageInfo = [[NSString alloc]initWithFormat:@"第%d页／共%d页",aCurrentPage,aTotolPage];
  [self showAlert:aCurrentPage withCount:aTotolPage];
}

- (void)showAlert:(NSUInteger)aCurrentPage withCount:(NSUInteger)aTotolPage{//页码
//  NSString *message = [[NSString alloc]initWithFormat:@"第%d页／共%d页",aCurrentPage,aTotolPage];
  UIWindow * window = [UIApplication sharedApplication].keyWindow;
  UIView *showview =  [[UIView alloc]init];
  showview.backgroundColor = [UIColor blackColor];
  showview.frame = CGRectMake(1, 1, 1, 1);
  showview.alpha = 1.0f;
  showview.layer.cornerRadius = 5.0f;
  showview.layer.masksToBounds = YES;
  [window addSubview:showview];
  
  UILabel *label = [[UILabel alloc]init];
  CGSize LabelSize = [m_pageInfo sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil]];
//  CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
  label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
  label.text = m_pageInfo;
  label.textColor = [UIColor whiteColor];
  label.textAlignment = 1;
  label.backgroundColor = [UIColor clearColor];
  label.font = [UIFont boldSystemFontOfSize:15];
  [showview addSubview:label];
  showview.frame = CGRectMake((self.frame.size.width - LabelSize.width - 20)/2, self.frame.size.height - 80, LabelSize.width+20, LabelSize.height+10);
  [UIView animateWithDuration:1.5 animations:^{
    showview.alpha = 0.5;
  } completion:^(BOOL finished) {
    [showview removeFromSuperview];
  }];
}

-(void)setLastButtonText:(NSString *)btnName{
   [lastButton setTitle:btnName forState:UIControlStateNormal];
}

-(void)OnChangeTheme:(int)nId{
  nThemeId = nId;
  UIColor *titleColor = [UIColor blackColor];
  if(nThemeId == 0){
    pTitleView.backgroundColor = _rgb2uic(0xe9e9e9, 1);;
    self.backgroundColor = [UIColor clearColor];
    m_tableView.backgroundColor = [UIColor clearColor];
    m_tableView.separatorColor=	_rgb2uic(0xe9e9e9,1);
  }else{
    pTitleView.backgroundColor = _rgb2uic(0x242431, 1);
    self.backgroundColor = _rgb2uic(0x2e303f,1);
    m_tableView.backgroundColor = _rgb2uic(0x2e303f,1);
    m_tableView.separatorColor=	_rgb2uic(0x3b4050,1);
    titleColor = _rgb2uic(0x8c96b4, 1);
  }
  
  for (int i=0; i<m_title_array.count; i++) {
    UIButton *btn = m_title_array[i];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
  }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *dataArray = self.m_data_array[indexPath.row];
    HZOwnedStockModel *model = [HZOwnedStockModel new];
    if ([[dataArray lastObject] isKindOfClass:[NSString class]]) {
        model.nModel_BlockId = [dataArray.lastObject intValue];
        model.model_Name = dataArray[0];
        [self.parent upToParentWithObjc:self withType:kHZ_BlockListDetailClick_Action withParamter:model];
    }else {
        CODELV_INFO codeInfo;
        [dataArray.lastObject getValue:&codeInfo];//索引最后个为codeInfo
        model.model_Name = [NSString stringWithUTF8String:codeInfo.name];
        model.model_Code = [NSString stringWithUTF8String:codeInfo.code];
        model.nModel_Market = codeInfo.market;
        model.nModel_Style = codeInfo.style;
        [self.parent upToParentWithObjc:self withType:kHZ_jumpSingleStock_Action withParamter:model];
    }
}


#pragma mark -
- (void)upToParentWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
}
- (void)downToChildWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
    switch (type) {
        case kHZ_updateNewData_Action:
        {
//            if ([paramter isKindOfClass:[NSArray class]]) {
//                [self p_updateNewData:paramter];
//            }
        }
            break;
            
        default:
            break;
    }
}

- (void)dealloc {
//  [pTitleView release];
//  [cellbgColor1 release];
//  [cellbgColor2 release];
//  [super dealloc];
//  //  [m_baseScrollView release];
//  //  [self release];
//  [m_data_array release];
//  [m_color_array release];
//  [m_title_array release];
}

@end

